package jp.dodododo.aop.intercept;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import jp.dodododo.aop.annotation.Enhance;

import org.aopalliance.intercept.ConstructorInvocation;

@Enhance(false)
public class DelegateMethodInvocation extends AbstractMethodInvocation implements ConstructorInvocation {

	private Method delegateMethod;

	public DelegateMethodInvocation(Method delegateMethod, Object target, Class<?> targetClass, AccessibleObject staticPart,
			Object... arguments) {
		super(target, targetClass, staticPart, arguments);
		this.delegateMethod = delegateMethod;
	}

	public Object proceed() throws Throwable {
		try {
			return delegateMethod.invoke(getThis(), getArguments());
		} catch (InvocationTargetException e) {
			Throwable cause = e.getCause();
			if (cause != null) {
				throw cause;
			} else {
				throw e;
			}
		}
	}

	public Constructor<?> getConstructor() {
		AccessibleObject staticPart = getStaticPart();
		if (staticPart instanceof Constructor) {
			return (Constructor<?>) staticPart;
		}
		return null;
	}
}
